
const qs = require('qs')
const path = require('path')
const permission = require('./permission')
const routerUtil = require('./util')
const beforeEnter = permission.beforeEnter
const routerMethodsKey = [
  'redirectTo',
  'switchTab',
  'reLaunch',
  'navigateTo'
]
// 对原生 router method 进行覆盖
routerMethodsKey.forEach(routerMethod => {
  const nativeRouteMethod = wx[ routerMethod ]
  Object.defineProperty(wx, routerMethod, {
    configurable: true,
    enumerable: true,
    writable: true,
    value: function(routerProp) {
      // 缓存原生路由方法 next
      // 如果 next 参数 存在则调用router.$go
      const nextRouteEnter = (nextProp) => {
        if (nextProp) {
          return routerUtil.$go(nextProp)
        }
        return nativeRouteMethod(routerProp)
      }
      // 路由劫持函数存在
      if (beforeEnter && typeof beforeEnter === 'function') {
        const pages = getCurrentPages()
        const fromPage = pages[ pages.length - 1 ]
        const [toRoutePath, toRouteQuery] = routerProp.url.split('?')
        const toRouteQueryOfObj = toRouteQuery ? qs.parse(toRouteQuery, {
          encode: false
        }) : {}
        const fromRouteAbsPath = '/' + fromPage.route

        let toRouteAbsPath = toRoutePath
        // 获取 to path 绝对路径
        if (toRoutePath.charAt(0) !== '/') {
          const dirList = fromPage.route.split('/')
          dirList.pop()
          const dirPath = dirList.join('/')
          toRouteAbsPath = '/' + path.join(dirPath, toRoutePath)
        }

        // to route 配置
        const toRoute = {
          path: toRouteAbsPath,
          query: toRouteQueryOfObj,
          method: routerMethod
        }
        // from route 配置
        const fromRoute = {
          path: fromRouteAbsPath,
          query: fromPage.options,
          method: routerMethod,
          page: fromPage
        }
        return beforeEnter(toRoute, fromRoute, nextRouteEnter)
      } else {
        return nextRouteEnter()
      }
    }
  })
})
